package com.haoran.dwz.web;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.haoran.dwz.domain.entities.ApiLog;
import com.haoran.dwz.rest.R;
import com.haoran.dwz.service.ApiLogService;
import com.haoran.dwz.wrapper.PaginationWrapper;

import io.swagger.annotations.ApiOperation;

 

 

@Controller
@RequestMapping(value = "apilog")
public class ApiLogController {
	
	@Autowired
	private ApiLogService apiLogService;
	
	@RequestMapping(value="/lastMonthStatistics", method = { RequestMethod.POST })
	@ResponseBody
	public R lastMonthStatistics() {
		Map<String, Object> lastMonthStatistics = apiLogService.lastMonthStatistics(6);
		return R.success(lastMonthStatistics);
	}
	
	@RequestMapping(value = "/index", method = { RequestMethod.GET })
	public String index(Model model) {
		return "log/apilog";
	}
	
	@ApiOperation("分页查询所有的API记录")
	@RequestMapping(value = "/page-list", method = { RequestMethod.GET })
	@ResponseBody
	public PaginationWrapper findByPageable(ApiLog apiLog) {
		Sort sort;
		if(StringUtils.isNotBlank(apiLog.getSidx()) && StringUtils.isNotBlank(apiLog.getOrder())){
			Direction direction =	"DESC".equalsIgnoreCase(apiLog.getOrder())? Direction.DESC:Direction.ASC;
			sort = new Sort(direction, apiLog.getSidx());
		}else{
			sort = new Sort(Direction.DESC, "requestTime", "responseTime");
		}
		Pageable pageable = new PageRequest(apiLog.getPage()-1, apiLog.getLimit(), sort);
		Page<ApiLog> entryByPageable = apiLogService.findByPageable(apiLog,pageable);
		PaginationWrapper pageUtil = new PaginationWrapper(entryByPageable.getContent(), entryByPageable.getTotalElements(), apiLog.getLimit(),	apiLog.getPage());
		return pageUtil;
	}
	
	@ApiOperation("删除接口日志")
	@RequestMapping(value = "remove", method = RequestMethod.POST)
	@ResponseBody
	public R delete(@RequestParam("ids[]") int[] ids) {
		if (ids == null || ids.length == 0) {
			return R.success();
		} else {
			for (int id : ids) {
				if (apiLogService.exists(id)) {
					apiLogService.delete(id);
				}
			}
			return R.success();
		}
	}
}
